package cn.piggy.type;

import cn.piggy.config.ConfigParam;
import cn.piggy.model.translation.QueryBody;
import cn.piggy.model.translation.TranRequestBody;
import cn.piggy.util.TokenStorageUtil;
import okhttp3.FormBody;
import okhttp3.Request;
import java.io.IOException;

public class TranslationType extends AiTypeBase {

    @Override
    public String getHost(Object object) throws IOException {
        if(object instanceof TranRequestBody){
            return ConfigParam.getConfigParam().getCreateHost();
        }else if(object instanceof QueryBody){
            return ConfigParam.getConfigParam().getQueryHost();
        }
        throw new RuntimeException("not find request url");
    }

    @Override
    public String queryToken() throws IOException {
        String token = TokenStorageUtil.tokens.get(this.getClass().getSimpleName() + "#TOKEN");
        if(token==null){
            synchronized (TranslationType.class){
                token = TokenStorageUtil.tokens.get(this.getClass().getSimpleName() + "#TOKEN");
                if(token==null){
                    String clientId = ConfigParam.getConfigParam().getApiKey();
                    String clientSecret = ConfigParam.getConfigParam().getSecretKey();
                    String authHost = ConfigParam.getConfigParam().getAuthHost();
                    FormBody formBody = new FormBody.Builder()
                            .add("grant_type","client_credentials")
                            .add("client_id",clientId)
                            .add("client_secret",clientSecret).build();
                    Request request = new Request.Builder().url(authHost)
                            .addHeader("Content-Type", "x-www-form-urlencoded").post(formBody).build();
                    token = requestToken(request);
                    TokenStorageUtil.tokens.put(this.getClass().getSimpleName() + "#TOKEN", token);
                }
            }
        }
        return token;
    }
}
